<template>
    <div class="lottery-detail-container">
        <div class="page-header">
            <div>
                <h2>抽奖活动详情</h2>
                <el-tag :type="getStatusType(lottery.status)" class="status-tag">
                    {{ formatStatus(lottery.status) }}
                </el-tag>
            </div>
            <div class="action-buttons">
                <el-button @click="goBack">返回列表</el-button>
                <el-button v-if="lottery.status === 'pending'" type="success" @click="publishLottery">
                    发布活动
                </el-button>
                <el-button v-if="lottery.status === 'active'" type="warning" @click="drawLotteryNow">
                    手动开奖
                </el-button>
                <el-button v-if="['pending', 'active'].includes(lottery.status)" type="danger"
                    @click="cancelLotteryEvent">
                    取消活动
                </el-button>
            </div>
        </div>

        <el-card v-loading="loading">
            <div class="detail-section">
                <h3>基本信息</h3>
                <div class="detail-content">
                    <div class="detail-item">
                        <span class="label">活动ID:</span>
                        <span>{{ lottery._id }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">活动名称:</span>
                        <span>{{ lottery.title }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">所属群组:</span>
                        <span>{{ groupName }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">奖品:</span>
                        <span>{{ lottery.prize }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">参与人数:</span>
                        <span>{{ lottery.maxParticipants }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">中奖人数:</span>
                        <span>{{ lottery.winnerCount }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">消耗积分:</span>
                        <span>{{ lottery.pointsCost }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">开奖方式:</span>
                        <span>
                            <el-tag :type="getDrawModeType(lottery.drawMode)">
                                {{ formatDrawMode(lottery.drawMode) }}
                            </el-tag>
                        </span>
                    </div>
                    <div class="detail-item" v-if="lottery.drawMode === 'auto'">
                        <span class="label">延迟开奖:</span>
                        <span>{{ lottery.delaySeconds || 0 }}秒</span>
                    </div>
                    <div class="detail-item" v-if="lottery.drawAt">
                        <span class="label">定时开奖:</span>
                        <span>{{ formatDate(lottery.drawAt) }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">赞助商:</span>
                        <span>{{ lottery.sponsor }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">联系方式:</span>
                        <span>{{ lottery.sponsorContact }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">领奖说明:</span>
                        <span>{{ lottery.rewardInfo || '领取奖品请联系本群管理员' }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">频道要求:</span>
                        <el-tag v-if="lottery.requireChannel" type="success">
                            必须关注 {{ lottery.channelLink }}
                        </el-tag>
                        <el-tag v-else type="info">不需要关注频道</el-tag>
                    </div>
                    <div class="detail-item" v-if="lottery.requireChannel">
                        <span class="label">频道链接:</span>
                        <span>{{ lottery.channelLink }}</span>
                    </div>
                    <div class="detail-item" v-if="lottery.requireChannel">
                        <span class="label">频道验证:</span>
                        <el-tag :type="lottery.channelVerificationStatus ? 'success' : 'warning'">
                            {{ lottery.channelVerificationStatus ? '正常' : '需要配置' }}
                        </el-tag>
                        <el-tooltip v-if="!lottery.channelVerificationStatus" effect="dark"
                            content="机器人需要是频道管理员才能验证用户是否关注" placement="top">
                            <el-icon class="warning-icon">
                                <warning />
                            </el-icon>
                        </el-tooltip>
                    </div>
                    <div class="detail-item">
                        <span class="label">创建时间:</span>
                        <span>{{ formatDate(lottery.createdAt) }}</span>
                    </div>
                    <div class="detail-item" v-if="lottery.startedAt">
                        <span class="label">开始时间:</span>
                        <span>{{ formatDate(lottery.startedAt) }}</span>
                    </div>
                    <div class="detail-item" v-if="lottery.endedAt">
                        <span class="label">结束时间:</span>
                        <span>{{ formatDate(lottery.endedAt) }}</span>
                    </div>
                </div>
            </div>

            <div class="participants-section">
                <h3>参与者列表 <el-tag v-if="autoRefresh" type="success" size="small">自动刷新中</el-tag></h3>
                <div class="table-actions">
                    <el-switch v-model="autoRefresh" active-text="自动刷新" inactive-text="手动刷新"
                        @change="handleAutoRefreshChange" />
                    <el-button type="primary" size="small" :icon="Refresh" @click="fetchLotteryDetails">刷新数据</el-button>
                </div>

                <el-table :data="participants" style="width: 100%" max-height="400" v-loading="participantsLoading">
                    <el-table-column prop="username" label="用户名" min-width="120">
                        <template #default="scope">
                            @{{ scope.row.username || scope.row.userId }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="firstName" label="姓名" min-width="120" />
                    <el-table-column prop="joinedAt" label="参与时间" min-width="180">
                        <template #default="scope">
                            {{ formatDate(scope.row.joinedAt, true) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="isWinner" label="是否中奖" min-width="100">
                        <template #default="scope">
                            <el-tag v-if="scope.row.isWinner" type="success">已中奖</el-tag>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="detail-section" v-if="lottery.winners && lottery.winners.length > 0">
                <h3>中奖者列表</h3>
                <div class="winners-list">
                    <div v-for="winner in lottery.winners" :key="winner.userId" class="winner-item">
                        <el-tag type="success">{{ winner.username || winner.userId }}</el-tag>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
import { ref, onMounted, computed, onUnmounted, reactive, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getLotteryDetail, getLotteryParticipants, drawLottery, cancelLottery, pollLotteryParticipants, publishLotteryApi } from '../../../api/lottery';
import { getGroups } from '../../../api/group';
import { formatDate } from '../../../utils/format';
import request from '../../../utils/request';
import { Refresh } from '@element-plus/icons-vue';

export default {
    name: 'LotteryDetail',
    setup() {
        const router = useRouter();
        const route = useRoute();
        const loading = ref(false);
        const lottery = ref({});
        const participants = ref([]);
        const groupList = ref([]);
        const autoRefresh = ref(true);
        const participantsLoading = ref(false);
        let refreshTimer = null;
        let pollingController = null;

        // 获取群组名称
        const groupName = computed(() => {
            const group = groupList.value.find(g => g.groupId === lottery.value.groupId);
            return group ? group.name : lottery.value.groupId;
        });

        // 获取抽奖活动详情
        const fetchLotteryDetails = async () => {
            if (loading.value) return;

            loading.value = true;
            try {
                const lotteryId = route.params.id;
                const res = await getLotteryDetail(lotteryId);
                if (res.data && res.data.success) {
                    lottery.value = res.data.data.event;
                    participants.value = res.data.data.participants || [];
                }
            } catch (error) {
                console.error('获取抽奖详情失败:', error);
                ElMessage.error('获取抽奖详情失败');
            } finally {
                loading.value = false;
            }
        };

        // 获取群组列表
        const fetchGroups = async () => {
            try {
                console.log('抽奖详情页面 - 开始获取群组列表');
                const res = await getGroups();
                console.log('抽奖详情页面 - 获取到的群组数据:', res);

                if (res && res.data && res.data.success) {
                    groupList.value = res.data.data.map(group => ({
                        groupId: group.groupId,
                        name: group.name
                    }));
                } else {
                    console.warn('获取群组列表返回非成功状态:', res);
                }
            } catch (error) {
                console.error('获取群组列表错误，但不影响主要功能:', error);
            }
        };

        // 格式化状态
        const formatStatus = (status) => {
            const statusMap = {
                'pending': '待发布',
                'active': '进行中',
                'completed': '已完成',
                'cancelled': '已取消'
            };
            return statusMap[status] || status;
        };

        // 获取状态标签类型
        const getStatusType = (status) => {
            const typeMap = {
                'pending': 'info',
                'active': 'success',
                'completed': 'primary',
                'cancelled': 'danger'
            };
            return typeMap[status] || '';
        };

        // 格式化抽奖模式
        const formatDrawMode = (drawMode) => {
            const modeMap = {
                'auto': '人满自动开奖',
                'time': '定时开奖',
                'manual': '手动开奖'
            };
            return modeMap[drawMode] || drawMode || '未设置';
        };

        // 获取抽奖模式标签类型
        const getDrawModeType = (drawMode) => {
            const typeMap = {
                'auto': 'success',
                'time': 'primary',
                'manual': 'warning'
            };
            return typeMap[drawMode] || 'info';
        };

        // 发布抽奖活动
        const publishLottery = async () => {
            try {
                await ElMessageBox.confirm('确定要发布该抽奖活动吗？发布后将立即生效。', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                loading.value = true;
                try {
                    const res = await publishLotteryApi(lottery.value._id);
                    if (res.data && res.data.success) {
                        ElMessage.success('抽奖活动已发布');
                        fetchLotteryDetails();
                    } else {
                        ElMessage.error(res.data?.message || '发布失败');
                    }
                } catch (error) {
                    console.error('发布抽奖活动失败:', error);
                    ElMessage.error('发布抽奖活动失败');
                } finally {
                    loading.value = false;
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('发布确认取消');
                }
            }
        };

        // 取消抽奖活动
        const cancelLotteryEvent = async () => {
            try {
                await ElMessageBox.confirm('确定要取消该抽奖活动吗？已消耗的积分将会退还。', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                loading.value = true;
                try {
                    const res = await cancelLottery(lottery.value._id);
                    if (res.success) {
                        ElMessage.success('抽奖活动已取消');
                        fetchLotteryDetails();
                        stopPolling();
                    } else {
                        ElMessage.error(res.message || '取消失败');
                    }
                } catch (error) {
                    console.error('取消抽奖活动失败:', error);
                    ElMessage.error('取消抽奖活动失败');
                } finally {
                    loading.value = false;
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('取消确认取消');
                }
            }
        };

        // 手动开奖
        const drawLotteryNow = async () => {
            try {
                await ElMessageBox.confirm('确定立即开奖吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                loading.value = true;
                try {
                    const res = await drawLottery(lottery.value._id);
                    if (res.success) {
                        ElMessage.success('开奖成功');
                        fetchLotteryDetails();
                        stopPolling();
                    } else {
                        ElMessage.error(res.message || '开奖失败');
                    }
                } catch (error) {
                    console.error('开奖失败:', error);
                    ElMessage.error('开奖失败');
                } finally {
                    loading.value = false;
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('开奖确认取消');
                }
            }
        };

        // 开始自动刷新
        const startAutoRefresh = () => {
            stopAutoRefresh(); // 先停止现有的定时器
            if (autoRefresh.value) {
                refreshTimer = setInterval(fetchLotteryDetails, 10000); // 每10秒刷新一次
            }
        };

        // 停止自动刷新
        const stopAutoRefresh = () => {
            if (refreshTimer) {
                clearInterval(refreshTimer);
                refreshTimer = null;
            }
        };

        // 处理自动刷新开关变化
        const handleAutoRefreshChange = (val) => {
            if (val) {
                startAutoRefresh();
                ElMessage.success('已开启自动刷新');
            } else {
                stopAutoRefresh();
                ElMessage.info('已关闭自动刷新');
            }
        };

        // 轮询参与者信息
        const startPolling = () => {
            pollingController = pollLotteryParticipants(route.params.id, 3000);

            pollingController.start((newParticipants) => {
                participants.value = newParticipants;
            });
        };

        // 停止轮询
        const stopPolling = () => {
            if (pollingController) {
                pollingController.stop();
                pollingController = null;
            }
        };

        // 返回列表
        const goBack = () => {
            router.push('/admin/points/lottery');
        };

        onMounted(() => {
            console.log('抽奖详情页面 - 组件已挂载');
            fetchGroups();
            fetchLotteryDetails();
            startAutoRefresh();
        });

        onBeforeUnmount(() => {
            stopAutoRefresh();
            stopPolling();
        });

        return {
            lottery,
            participants,
            loading,
            groupName,
            formatDate,
            formatStatus,
            getStatusType,
            publishLottery,
            cancelLotteryEvent,
            drawLotteryNow,
            goBack,
            autoRefresh,
            handleAutoRefreshChange,
            Refresh,
            participantsLoading,
            formatDrawMode,
            getDrawModeType
        };
    }
};
</script>

<style scoped>
.lottery-detail-container {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
}

.status-tag {
    margin-left: 10px;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.detail-section {
    margin-bottom: 30px;
}

.detail-section h3 {
    margin-top: 0;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
    color: #303133;
}

.detail-content {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
}

.detail-item {
    display: flex;
    line-height: 24px;
}

.detail-item .label {
    min-width: 100px;
    color: #606266;
    font-weight: bold;
}

.winners-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.winner-item {
    margin-right: 10px;
    margin-bottom: 10px;
}

.participants-section {
    margin-bottom: 30px;
}

.participants-section h3 {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.table-actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 16px;
    gap: 16px;
}
</style>